package com.rybbaby.tss.front.tssClassesLessons.controller;

import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssClasses.entity.TssClasses;
import com.rybbaby.tss.front.tssClasses.entity.ViewClassesAttendanceManagement;
import com.rybbaby.tss.front.tssClasses.service.ITssClassesService;
import com.rybbaby.tss.front.tssClassesLessons.entity.TssClassesLessons;
import com.rybbaby.tss.front.tssClassesLessons.service.ITssClassesLessonsService;
import com.rybbaby.tss.front.tssMemberAttendClassRecord.entity.TssMemberAttendClassRecord;
import com.rybbaby.tss.front.tssMemberAttendClassRecord.service.ITssMemberAttendClassRecordService;
import com.rybbaby.tss.front.tssMemberPackage.entity.TssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.front.tssStudent.service.ITssStudentService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author 雷春琼
 * @description 班级表管理
 * @createDate 2017-08-09 下午11:50:14
 */
@Controller
@RequestMapping(value = "tssClassesLessonsController")
public class TssClassesLessonsController extends BaseController {


    @Autowired
    private ITssClassesService tssClassesService;
    @Autowired
    private ITssClassesLessonsService tssClassesLessonsService;
    @Autowired
    private ITssMemberAttendClassRecordService tssMemberAttendClassRecordService;
    @Autowired
    private ITssMemberPackageService tssMemberPackageService;
    @Autowired
    private ITssStudentService tssStudentService;

    /**
     * 获取班级表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取班级表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssClassesList", method = RequestMethod.POST)
    public ModelAndView tssClassesList(TssClasses entity, PageBean paramPageBean, @RequestParam(required = false) Integer type) {
        ModelAndView mav = null;
        try {
            if (type == 1) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesListView"));
            } else if (type == 2) {
                mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitClassesListView"));
            }
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(TssClasses.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            dc.add(Restrictions.eq("type", type));
            PageBean pageBean = tssClassesLessonsService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 获取班级表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取班级表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "classAttendance", method = RequestMethod.POST)
    public ModelAndView classAttendance(ViewClassesAttendanceManagement entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewClassesAttendanceManagementView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(ViewClassesAttendanceManagement.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = tssClassesLessonsService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param entity       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到班级表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(TssClasses entity, @RequestParam(required = true) String serializeNum) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesEditView"));
        if (entity != null && entity.getId() != null) {
            TssClassesLessons editEntity = this.tssClassesLessonsService.get(entity.getId());
            mav.addObject("editEntity", editEntity);
            mav.addObject("editModel", "edit");
        } else {
            mav.addObject("editModel", "add");
        }
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存班级表对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(TssClassesLessons entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            if (StringUtils.isNotBlank(id)) {
                TssClassesLessons destEntity = this.tssClassesLessonsService.get(id);
                BeanUtils.copyProperties(entity, destEntity, "startDate", "endDate", "changeTime", "createTime", "updateTime");
                this.tssClassesLessonsService.updateEntitiy(destEntity);
            } else {
                entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
                Serializable newId = this.tssClassesLessonsService.save(entity);
                if (newId == null) {
                    ajr.setResCode(301);
                    ajr.setResMsg("保存失败!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssClassesLessonsService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssClassesLessonsService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }


    /**
     * 根据班级id查询班级对应课节信息
     *
     * @param entity
     * @param serializeNum
     * @param classId
     * @return
     */
    @RequestLog(content = "根据班级id查询班级对应课节信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getListByClassId", method = RequestMethod.GET)
    public ModelAndView getListByClassId(TssMemberAttendClassRecord entity, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) String classId, @RequestParam(required = true) String memberPackageId) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssClassesLessonsDetailListView"));
        List<Map<String, Object>> classesMapList = new ArrayList<>();
        if (StringUtils.isNotBlank(classId)) {
            classesMapList = tssClassesService.batchQueryById(classId);
            List<Map<String, Object>> lessonsList = new ArrayList<>();
            //查询是否有过报班记录
            List<Map<String, Object>> attendClassIdList = new ArrayList<>();
            for (Map<String, Object> classesMap : classesMapList) {
                /*attendClassIdList = this.tssMemberAttendClassRecordService.findAttendClassByClassIdAndMemberPackageId(memberPackageId, classesMap.get("id").toString());
                if (attendClassIdList.size() == 0) {
                    lessonsList = this.tssMemberAttendClassRecordService.findCouldClassLessonInfoByClassIdAndMemberPackageId(classesMap.get("id").toString());
                    classesMap.put("lessonsList", lessonsList);
                } else {*/
                   /* StringBuffer buf = new StringBuffer();
                    for (Map<String, Object> map : attendClassIdList) {
                        buf = buf.append(map.get("id").toString()).append(",");
                    }
                    String lessonIds = StringUtils.join(buf.toString().split(","), "','");*/
                    lessonsList = this.tssMemberAttendClassRecordService.findCouldClassLessonInfoByClassIdAndMemberPackageId(memberPackageId, classesMap.get("id").toString());
                    classesMap.put("lessonsList", lessonsList);
              /*  }*/
            }
        }
        //查询会员课时包
        TssMemberPackage memberPackage = this.tssMemberPackageService.get(memberPackageId);
        //查询会员信息
        TssStudent student = this.tssStudentService.get(memberPackage.getMemberId());
        mav.addObject("type", memberPackage.getType());
        mav.addObject("surplusAttendanceDay", memberPackage.getSurplusAttendanceDay());
        mav.addObject("surplusClassHour", memberPackage.getSurplusClassHour());
        mav.addObject("stuName", student.getName());
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("memberPackageId", memberPackageId);
        mav.addObject("listMap", classesMapList);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 根据班级id查询班级对应课节信息
     *
     * @param entity
     * @param serializeNum
     * @param classId
     * @return
     */
    @RequestLog(content = "根据班级id查询班级对应课节信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "getListByChangeClassId", method = RequestMethod.GET)
    public ModelAndView getListByChangeClassId(TssMemberAttendClassRecord entity, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) String classId, @RequestParam(required = true) String targetDataId,@RequestParam(required = true) String memberPackageId) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssChangeClassesLessonsDetailListView"));
        List<Map<String, Object>> classesMapList = new ArrayList<>();
        if (StringUtils.isNotBlank(classId)) {
            classesMapList = tssClassesService.batchQueryById(classId);
            for (Map<String, Object> classesMap : classesMapList) {
                List<Map<String, Object>> lessonsList = this.tssClassesLessonsService.getListByClassId(classesMap.get("id").toString());
                classesMap.put("lessonsList", lessonsList);
            }
        }
        //查询会员课时包
        TssMemberPackage memberPackage = this.tssMemberPackageService.get(memberPackageId);
        Integer surplusClassHour =  tssClassesLessonsService.getSurplusCurriculum(targetDataId, memberPackage.getMemberId());
        //查询会员信息
        TssStudent student = this.tssStudentService.get(memberPackage.getMemberId());
        mav.addObject("targetDataId", targetDataId);
        mav.addObject("classId", classId);
        mav.addObject("surplusClassHour", surplusClassHour);
        mav.addObject("stuName", student.getName());
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("memberPackageId", memberPackageId);
        mav.addObject("listMap", classesMapList);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }


    /**
     * 根据课节上课时间查询课节信息班级对调
     *
     * @param classTime
     * @param classType
     * @return
     */
    @RequestLog(content = "根据课节上课时间查询课节信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "classLessonsExchangeByClassTime", method = RequestMethod.GET)
    public String classLessonsExchangeByClassTime(@RequestParam(required = true) String classTime, @RequestParam(required = true) Integer classType) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            Map<String, Object> classLessons = this.tssClassesLessonsService.classLessonsExchangeByClassTime(classTime, classType);
            ajr.setData(classLessons);
        } catch (Exception e) {
            throw e;
        }
        return ajr.jsonResponse(true);
    }


    /**
     * 修改班级对调时间
     *
     * @return
     */
    @RequestLog(content = "修改班级对调时间", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "updateLessonClassTime", method = RequestMethod.GET)
    public String updateLessonClassTime(@RequestParam(required = true) String lessonsOne, @RequestParam(required = true) String classTimeOne, @RequestParam(required = true) String lessonsTwo, @RequestParam(required = true) String classTimeTwo) throws Exception {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String adminUserId = super.getLoginUser().getId();
            Boolean bool = this.tssClassesLessonsService.updateLessonClassTime(lessonsOne, classTimeOne, lessonsTwo, classTimeTwo, adminUserId);
            if (bool) {
                ajr.setResCode(200);
                ajr.setResMsg("保存成功!");
            } else {
                ajr.setResCode(301);
                ajr.setResMsg("保存失败!");
            }
        } catch (Exception e) {
            throw e;
        }
        return ajr.jsonResponse(false);
    }


    /**
     * 停课
     *
     * @param lessonIds 停课的课节id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "停课", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "stopClassByLessonIds", method = RequestMethod.GET)
    public String stopClassByLessonIds(@StringValidator(nullable = false) String lessonIds) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("停课成功!");
            if (StringUtils.isNotBlank(lessonIds)) {
                this.tssClassesLessonsService.stopClassByLessonIds(lessonIds);
            } else {
                ajr.setResMsg("停课失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("停课失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }


    /**
     * 根据老师和上课时间查询可以报班的课节信息
     *
     * @param empAdminUserId
     * @param classTime
     * @return
     */
    @ResponseBody
    @RequestLog(content = "根据课节上课时间查询课节信息", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "queryByClassTimeAndAdminUserId", method = RequestMethod.GET)
    public String queryByClassTimeAndAdminUserId(@RequestParam(required = true) String classTime, @RequestParam(required = true) String empAdminUserId, @RequestParam(required = true) String memberPackageId) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            TssMemberPackage memberPackage = this.tssMemberPackageService.get(memberPackageId);
            List<Map<String, Object>> listMap = this.tssClassesLessonsService.queryByClassTimeAndAdminUserId(empAdminUserId, classTime, memberPackage.getType());
            ajr.setData(listMap.toArray());
        } catch (Exception e) {
            throw e;
        }
        return ajr.jsonResponse(true);
    }


}
